package ufpb.compiladores.lexico.tests;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import ufpb.compiladores.lexico.Reader;
import org.junit.*;
/**
 *
 * @author seminick
 */
public class ReaderTest {
    
    private Reader reader = null;
    private File tmp = null;
    private String teste = "abcdefg";
    
    @Before
    public void init() {
        
        try {
            
            tmp = File.createTempFile("compiladores_teste", null);
            FileOutputStream out = new FileOutputStream(tmp);
            out.write(teste.getBytes());
            out.flush();
            out.close();
            reader = new Reader(tmp);
        } catch (IOException io) {
            
            Assert.fail("Not possible to create temp file");
        }
    }
    
    @Test
    public void readTest() {
        
        StringBuilder to = new StringBuilder();
        StringBuilder rev = new StringBuilder();
        int len = teste.length();
        
        for (int i = 0; i < len; i++) {
            
            if (i != len - 1) {
                
                Assert.assertTrue("Has next char return false at " + i, reader.hasNextCharacter());
            }
            
            Assert.assertTrue("next char return false at " + i, reader.nextCharacter());
            
            to.append(reader.getCurrentCharacter());
        }
        
         
        Assert.assertFalse("hasNextCharacter return true at end", reader.hasNextCharacter());
        Assert.assertFalse("nextCharacter return true at end", reader.nextCharacter());
            
        
        Assert.assertEquals(teste, to.toString());
        
        int i = len - 1;
        do {

            rev.append(reader.getCurrentCharacter());
            if (i != 0) {

                Assert.assertTrue("hasPreviousCharacter return false at " + i, reader.hasPreviousCharacter());
                Assert.assertTrue("previousCharacter return false", reader.previousCharacter());
            }
            i--;
        } while (i >= 0);
        
        Assert.assertFalse("hasPreviousCharacter return true at end", reader.hasPreviousCharacter());
        Assert.assertFalse("previousCharacter return false", reader.previousCharacter());
        
        Assert.assertEquals(rev.reverse().toString(), teste);
    }
    
    @After
    public void down() {
        
        this.reader.close();
    }
}
